package larrys.pomodoro.daoimpl;

import java.util.List;
import static java.sql.Types.VARCHAR;

import larrys.pomodoro.daoimpl.rowmappers.RoleRowMapper;
import larrys.pomodoro.domain.entity.Role;
import larrys.pomodoro.domain.repository.BaseInfoRepository;
import larrys.pomodoro.util.AssertUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class BaseInfoRepositoryImpl implements BaseInfoRepository {

	private static Log logger = LogFactory.getLog(BaseInfoRepositoryImpl.class);
	private JdbcTemplate jdbcTemplate;

	@Required
	@Autowired
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	private final static String SQL_QUERY_ALL_ROLES = "SELECT id, role_name FROM role";

	@Override
	public List<Role> getAllRoles() {
		logger.debug("Trying to get all Roles");
		List<Role> roles = jdbcTemplate.query(SQL_QUERY_ALL_ROLES,
				new RoleRowMapper());
		logger.debug("Returning all " + roles);
		return roles;
	}

	private final static String SQL_QUERY_ROLE_BY_NAME = "SELECT id, role_name FROM role WHERE role_name=?";

	@Override
	public Role getRoleByName(String name) {
		AssertUtil.argumentNotNull(name, "name");
		logger.debug("Trying to get Role[roleName:" + name + "]");
		List<Role> roles = jdbcTemplate.query(SQL_QUERY_ROLE_BY_NAME,
				new Object[] { name }, new int[] { VARCHAR },
				new RoleRowMapper());
		if (roles.size() == 1) {
			logger.debug("Returning all " + roles.get(0));
			return roles.get(0);
		} else if (roles.size() > 1) {
			String message = "Role with[roleName:" + name
					+ "] has found more then one!";
			logger.fatal(message);
			throw new RuntimeException(message);
		} else {
			logger.warn("Role[roleName:" + name + "] doesn't exist!");
			return null;
		}
	}
}
